package com.xavier.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xavier.convertor.DeptConvertor;
import com.xavier.dao.DeptMapper;
import com.xavier.dto.DeptDTO;
import com.xavier.dto.DeptQueryDTO;
import com.xavier.model.Dept;
import com.xavier.result.ResultCode;
import com.xavier.service.IDeptService;
import com.xavier.utils.ServiceException;
import com.xavier.utils.XavierLambdaQueryWrapper;
import com.xavier.vo.DeptDetailVO;
import com.xavier.vo.DeptPageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * 业务逻辑层-部门实现类
 *
 * @author Xavier
 * @version 1.0
 */
@Slf4j
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDept(Long id) {
        getBaseDept(id);
        return super.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createDept(DeptDTO dto) {
        Dept dept = DeptConvertor.toDept(dto);
        dept.setId(null);
        super.save(dept);
        return dept.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDept(DeptDTO dto) {
        getBaseDept(dto.getId());
        Dept dept = DeptConvertor.toDept(dto);
        return super.updateById(dept);
    }

    @Override
    public DeptDetailVO getDept(Long id) {
        return DeptConvertor.toDeptDetailVO(getBaseDept(id));
    }


    @Override
    public Dept getBaseDept(Long id) {
        Dept dept = super.getById(id);
        if (Objects.isNull(dept) || dept.getIsDeleted()) {
            throw new ServiceException(ResultCode.COMMON_MESSAGE, "部门不存在");
        }
        return dept;
    }

    @Override
    public List<DeptPageVO> getList(DeptQueryDTO dto) {
        XavierLambdaQueryWrapper<Dept> wrapper = Dept.gw().likeIfPresent(Dept::getDeptName, dto.getDeptName());
        List<Dept> list = super.list(wrapper);
        return DeptConvertor.toDeptPageVOList(list);
    }

}
